import xml.etree.ElementTree as ET
import logging
import os
import sys

def get_resource_path(relative_path):
    """获取资源文件的绝对路径"""
    try:
        # PyInstaller创建临时文件夹,将路径存储在_MEIPASS中
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")
    
    return os.path.join(base_path, relative_path)

class FieldInfo:
    def __init__(self, name: str, field_type: str, length: int, description: str = ""):
        self.name = name
        self.type = field_type
        self.length = length
        self.description = description
        self.valid_values = {}
        
    def add_valid_value(self, value: int, description: str):
        self.valid_values[value] = description
        
    def get_value_description(self, value: int) -> str:
        return self.valid_values.get(value, str(value))

class FrameSchemaParser:
    def __init__(self, schema_file: str):
        self.logger = logging.getLogger('frame_analyzer')
        self.fields = {}
        self.total_length = 0
        schema_file = get_resource_path(schema_file)
        self._parse_schema(schema_file)
        
    def _parse_schema(self, schema_file: str):
        """解析帧格式定义文件"""
        try:
            tree = ET.parse(schema_file)
            root = tree.getroot()
            
            # 解析头部字段
            for field in root.findall('.//field'):
                name = field.get('name')
                field_type = field.get('type')
                length = int(field.get('length'))
                
                # 创建字段信息对象
                field_info = FieldInfo(name, field_type, length)
                
                # 获取字段描述
                desc_elem = field.find('description')
                if desc_elem is not None:
                    field_info.description = desc_elem.text
                
                # 获取有效值定义
                valid_values = field.find('valid_values')
                if valid_values is not None:
                    for value in valid_values.findall('value'):
                        value_id = int(value.get('id'), 16 if '0x' in value.get('id') else 10)
                        field_info.add_valid_value(value_id, value.text)
                
                self.fields[name] = field_info
                self.total_length += length
                
                self.logger.debug(f"创建字段: {name}, 类型: {field_type}, 长度: {length}")
                
            self.logger.info(f"成功加载帧格式定义，总字段数: {len(self.fields)}")
            
        except Exception as e:
            self.logger.error(f"解析帧格式定义失败: {str(e)}")
            raise
            
    def get_field_info(self, field_name: str) -> FieldInfo:
        """获取字段信息"""
        return self.fields[field_name]
        
    def get_total_length(self) -> int:
        """获取帧总长度"""
        return self.total_length 